package com.example.s3demo.utils

import java.io.IOException
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.util.*
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec



object EncryptUtil {
    @JvmStatic
    @Throws(NoSuchAlgorithmException::class, UnsupportedEncodingException::class)
    fun encryptByMD5(str: String): String {
        //生成md5加密算法
        val md5 = MessageDigest.getInstance("MD5")
        md5.update(str.toByteArray(charset("UTF-8")))
        val b = md5.digest()
        var i: Int
        val buf = StringBuffer("")
        for (j in b.indices) {
            i = b[j].toInt()
            if (i < 0) i += 256
            if (i < 16) buf.append("0")
            buf.append(Integer.toHexString(i))
        }
        val md5_32 = buf.toString()
        return md5_32
    }

    private const val DES = "DES"
    private const val ENCODE = "UTF-8"
    private const val defaultKey = "LocalS3X"


    @Throws(Exception::class)
    fun encryptByDES(data: String): String {
        val bt = encrypt(data.toByteArray(charset(ENCODE)), defaultKey.toByteArray(charset(ENCODE)))
        val strs: String = Base64.getEncoder().encodeToString(bt)
        return strs
    }

    @Throws(IOException::class, Exception::class)
    fun decryptByDES(data: String?): String? {
        if (data == null) return null
        val buf: ByteArray = Base64.getDecoder().decode(data)
        val bt = decrypt(buf, defaultKey.toByteArray(charset(ENCODE)))
        return String(bt, charset(ENCODE))
    }

    @Throws(Exception::class)
    private fun encrypt(data: ByteArray, key: ByteArray): ByteArray {
        val sr = SecureRandom()
        val dks = DESKeySpec(key)
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        val cipher = Cipher.getInstance(DES)
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr)
        return cipher.doFinal(data)
    }

    @Throws(Exception::class)
    private fun decrypt(data: ByteArray, key: ByteArray): ByteArray {
        val sr = SecureRandom()
        val dks = DESKeySpec(key)
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        val cipher = Cipher.getInstance(DES)
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr)
        return cipher.doFinal(data)
    }
}
